<template>
	<view class="bg-gray ">

		<u-toast ref="uToast"></u-toast>
		<!-- <view class=" padding flex flex-direction">
			<button @tap="getSub()" class="cu-btn block bg-gradual-blue lg">
				订阅消息
			</button>
		</view>
		<view class=" padding flex flex-direction">
			<button @tap="notice()" class="cu-btn block bg-gradual-blue lg">
				发送订阅消息
			</button>
		</view> -->
		<view v-for="(item,index) in list2" :style="[{animationDelay: (index + 1)*0.1 + 's'}]" :key="item.id"
			class="dynamic  padding-lr-lg padding-top-lg wei_card_item" :class="[toggleDelay?'animation-slide-left':'']">

			<view style="border-radius: 10rpx;overflow: hidden;">
				<view class="cu-list menu-avatar" >
					<view class="cu-item" >
						<!-- :style="{width: 100/todoItem.todo_item_need_dos2.length+'%'}" -->
						<view class="cu-avatar round lg" :style="{backgroundImage:`url(${item.user.avatarUrl})`}">
							<view class="cu-tag badge"
								:class="item.user.user_gender==2?'cuIcon-male bg-pink':item.user.user_gender==1?'cuIcon-female bg-blue':'cuIcon-question bg-gray'">
							</view>
						</view>
						<view class="content flex-sub">
							<view>{{item.user.user_name}}</view>
							<view class="text-gray text-sm flex justify-between">
								<uni-dateformat format="yyyy年MM月dd日 hh:mm:ss" :date="item.created_at"></uni-dateformat>
							</view>
							
						</view>
						<view class=" flex padding-sm justify-between align-center bg-white" >
							<button class="cu-btn  shareBtn sm" type="default" :data-item='item' data-name="shareBtn" open-type="share">
								<text class="cuIcon-weixin text-olive"></text> 转发</button>
						</view>
					</view>
					
				</view>
				<view class="padding-lr bg-white">
					<view class="cu-progress radius striped active sm">
						<view class="bg-orange" :style="[{ width:loading?item.progress.unfinished1:''}]">
							{{item.progress.unfinished1}}
						</view>
						<view class="bg-olive" :style="[{ width:loading?item.progress.finishedData1:''}]">
							{{item.progress.finishedData1}}
						</view>
						<view class="bg-grey" :style="[{ width:loading?item.progress.todoData1:''}]">
							{{item.progress.todoData1}}
						</view>
					</view>
				</view>
				<view class="cu-card article" @click="cardClickHandler(item)" :class="isCard?'no-card':''">
					<view class="cu-item shadow">
						<view class="title">
							<view class="text-cut">{{item.todo_item_name}}</view>
						</view>
						<view class="content">
							<!-- 	<image src="https://ossweb-img.qq.com/images/lol/web201310/skin/big10006.jpg"
								mode="aspectFill"></image> -->
							<view class="desc">
								<view class="text-content"> {{item.todo_item_description||''}}
								</view>

								<view>
									<view class="cu-tag bg-gray light sm round">
										任务周期
										{{item.todo_item_task_cycle}}
									</view>
									<view class="cu-tag bg-gray light sm round">
										需要完成次数{{item.todo_item_need_nums }}</view>
									<view 
										v-if="item.todo_item_need_dos.length" class="cu-capsule  round margin-left-sm">
										<view class='cu-tag bg-gradual-orange  light sm'>今日待完成
										</view>
										<view class="cu-tag line-orange  sm">
											<text class='cuIcon-light text-orange'></text>
								
										</view>


									</view>

									<view v-else class="cu-tag bg-gradual-green light sm round">今日已完成</view>

								</view>

							</view>
						</view>
					</view>
				</view>

				<view class="text-gray text-sm text-right bg-white padding ">

					<text class="cuIcon-attentionfill  ">浏览{{item.todo_item_views}}</text>
				<!-- 	<text @tap.stop="Toggle(index,item,'todo_item_thumbs_up')"
						:class="[animation&&currentIndex==index?animation:'',animation&&currentIndex==index?'text-olive':'']"
						class="cuIcon-appreciatefill ">点赞{{item.todo_item_thumbs_up}}</text> -->
											
									
				</view>

			</view>
		</view>


	</view>
</template>

<script>
	import {
		update_todo_item_need_do_by_pk,
		delete_todo_item_by_pk,
		update_todo_item_by_pk,
		insert_todo_item_remind_one
	} from "@/common/api.js";
	import {
		checkAndRequestSubscribeMessage
	} from "@/common/utils.js"

	export default {

		watch: {
			// 计算进度条
			list(newValue, oldValue) {

				// created(){
				// 	console.log('组件初始化完成');
				// },
				if (newValue !== oldValue) {
					for (var s of this.list) {
						// console.log(s.todo_item_need_nums,"sss");
						let num = s.todo_item_need_nums // 任务总数

						let finished = s.finished.aggregate.count

						let todo = s.todo.aggregate.count

						let unfinished = num - finished - todo
						let progress = {
							unfinished1: unfinished === 0 ? '' : Math.round(100 / num * unfinished) + '%',
							finishedData1: finished === 0 ? '' : Math.round(100 / num * finished) + '%',
							todoData1: todo === 0 ? '' : Math.round(100 / num * todo) + '%',

						}
						// console.log(num,unfinished,finished,todo,progress);
						s.progress = progress


					}
					this.list2 = this.list
				}

			}
		},




		mounted() {
			console.log("mounted");
			this.userInfo = uni.getStorageSync("userInfo");
			
			if (!this.userInfo) {
				uni.showModal({
					content: "获取用户信息失败",
					complete() {
						uni.navigateTo({
							url: "/pages/login/index"
						})
					}
				})
			
				return
			}
			let that = this;

			this.ToggleDelay()


			setTimeout(function() {
				that.loading = true

			}, 500)


		},

		data() {
			return {
				userInfo:null,
				
				currentIndex: null,
				// 动画
				animation: '', // 点赞
				animationRemindHer: '', // 提醒他
				list3: [{
						name: 'fade',
						color: 'red'
					},
					{
						name: 'scale-up',
						color: 'orange'
					},
					{
						name: 'scale-down',
						color: 'olive'
					},
					{
						name: 'slide-top',
						color: 'green'
					}, {
						name: 'slide-bottom',
						color: 'cyan'
					},
					{
						name: 'slide-left',
						color: 'blue'
					},
					{
						name: 'slide-right',
						color: 'purple'
					},
					{
						name: 'shake',
						color: 'mauve'
					}
				],
				toggleDelay: false,

				list2: [],
				loading: false,
				// 卡片宽度
				isCard: true,
				// 添加目标按钮
				horizontal: "right",
				vertical: "bottom",
				direction: "horizontal",
				pattern: {
					color: "#7A7E83",
					backgroundColor: "#fff",
					selectedColor: "#007AFF",
					buttonColor: "#007AFF",
					iconColor: "#fff",
				},
				content: [{
					//   iconPath: "/static/image.png",
					//   selectedIconPath: "/static/image-active.png",
					text: "添加目标",
					active: false,
				}],
				mytoken: ''
			};
		},

		methods: {
			// 检查订阅消息权限，未开启提示前往开启，已开启请求订阅消息
			getSub() {
				checkAndRequestSubscribeMessage()
			},


			// 通知
			notice() {
				let that = this
				//下方的thing1，thing2和其他，对应的是你选取模板的模板详情中的字段名称(可在小程序后台模板查看对应的字段，要和上面的字段一样)，需要更改成你自己的
				const pushmsg = {
					"touser": 'o1jgE5h7Pj-QCm9-NG0EqMqvemDE',
					"template_id": that.$send_tmplIds,
					"data": {
						thing1: {
							value: '跳舞计划' //任务名称
						},
						thing4: {
							value: '每天晚上跳一会儿舞，身材会更好！' //任务描述
						},
						time10: {
							value: '2019年11月11日' //任务开始时间
						},
						time11: {
							value: '2019年11月11日' //任务结束时间
						},
					

					}
				}
				wx.request({
					url: 'https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=' +
						'65_HKpvwv0RJGLrGVOmapvDs-X0CxOcwxyqtkcGpZYlwDG2y_kxAvNMUvGzAbF3mQliU38yE62JLpIyn6Us3fp-CqchRDkZPFiMo5_9BgTAGk6uedEQj7tdwM3JubMXWOdAIACBT',
					data: JSON.stringify(pushmsg),
					method: 'POST',
					success: function(res) {
						console.log(res)
					}
				})
			},


			// 点赞
			async interactiveOperation(id = '', type = '', oldNums = 0) {
				const data = await update_todo_item_by_pk(id, type, oldNums)
					.then((res) => {

						if (
							res.code === 200 &&
							res.data?.update_todo_item_by_pk[type]
						) {
							return res.data?.update_todo_item_by_pk[type]
						}
					})
					.catch((err) => {
						console.log(err, "浏览量");
					});

				if (data) return data
			},
			// 动画
			Toggle(index, item, type) {
				let that = this
				this.currentIndex = index
				if (type === 'remindHer') {
					// 提醒他
					this.animationRemindHer = 'animation-scale-down';
					let message = '提醒+1!'
					let type = 'success'

				
					if (that.userInfo.id) {
						// 添加提醒数据
						let variables = {
							"object": {
								"todo_item_id": item.id,
								"remind_user_id": that.userInfo.id,
								// "content":'test'
							}
						}
						insert_todo_item_remind_one(variables).then(res => {
							console.log(res, "提醒res");
							if (res.code !== 200) {
								message = '提醒失败!'
								type = 'warning'
							} else {
								item.todo_item_reminds_aggregate.aggregate.count += 1
								that.$emit("update:list", that.list);
							}
						}).catch((err => {
							console.log(err, "提醒err");
							message = '提醒失败!'
							type = 'warning'
						}))
					} else {
						message = '提醒失败!'
						type = 'warning'
					}




					setTimeout(() => {
						this.animationRemindHer = '';
						this.currentIndex = null


						this.$refs.uToast.show({
							position: 'top',
							type,
							message,
							duration: '500'


						})
					}, 200)
				} else if (type === 'todo_item_thumbs_up') {
					// 点赞
					this.animation = 'animation-scale-down';

					setTimeout(() => {
						this.animation = '';
						this.currentIndex = null
					}, 200)

					// 调用点赞方法
					this.interactiveOperation(item.id, 'todo_item_thumbs_up', item.todo_item_thumbs_up)
						.then(res => {
							console.log(res);

							if (res) item.todo_item_thumbs_up = res
						}).catch(err => {
							console.log(err, "点赞|");
						})
				}

			},
			ToggleDelay() {
				this.toggleDelay = true;
				setTimeout(() => {
					this.toggleDelay = false
				}, 1000)
			},

			IsCard(e) {
				this.isCard = e.detail.value
			},
			// 点击卡片事件
			cardClickHandler(item) {

				uni.navigateTo({
					url: `/pages/todo_item_note/index?user_id=${item.user_id}&todo_item_id=${item.id}`,
				});
			},
			// 点击宫格
			gridItemClick(type, item, index) {
				let that = this;

				switch (type) {
					case "note":
						console.log("note");
						// 把需要传递的信息存入全局变量,在目的页面获取
						getApp().globalData.content = item;
						uni.navigateTo({
							url: `/pages/todo_item_note/index`,
						});
						break;
					case "ok":
						console.log("ok");
						uni.showModal({
							title: "提示",
							content: "是否确认完成了该目标?",
							success: function(res) {
								if (res.confirm) {
									console.log("用户点击确定");
									//完成当天任务,更新待执行任务数据
									update_todo_item_need_do_by_pk(item.todo_item_need_dos[0]
											.id)
										.then((res) => {
											console.log(res, "更新待执行任务数据");
											if (
												res.code === 200 &&
												res.data.update_todo_item_need_do_by_pk
											) {
												item.todo_item_need_dos = [];
												that.$emit("update:list", that.list);
											}
										})
										.catch((err) => {
											console.log(err, "更新待执行任务数据");
										});
								} else if (res.cancel) {
									console.log("用户点击取消");
								}
							},
						});
						break;
					case "edit":
						console.log("edit");
						// 把需要传递的信息存入全局变量,在目的页面获取
						getApp().globalData.content = item;
						uni.navigateTo({
							url: `/pages/index/todo-item-edit`,
						});
						break;
					case "deleteToDo":
						console.log("deleteToDo");

						delete_todo_item_by_pk(item.id)
							.then((res) => {
								console.log(res);
								if (res.code === 200) {
									uni.showToast({
										icon: "success",
										title: "删除成功!",
									});
									that.list.splice(index, 1);
									that.$emit("update:list", that.list);
								}
							})
							.catch((err) => {
								console.log(err);
							});
						break;

					default:
						break;
				}
			},
			trigger(e) {
				this.content[e.index].active = !e.item.active;
				console.log(e);
				uni.navigateTo({
					url: "/pages/index/todo-item-add",
				});
			},
			fabClick() {
				//   uni.showToast({
				//     title: "点击了悬浮按钮",
				//     icon: "none",
				//   });
			},
			close() {
				this.$refs.fab.close();
			},
		},


		onBackPress() {
			if (this.$refs.fab.isShow) {
				this.$refs.fab.close();
				return true;
			}
			return false;
		},
		props: {
			list: {
				type: Array,
				default () {
					return [];
				},
			},
		},
	};
</script>

<style lang="scss" scoped>
	image[class*="gif-"] {
		border-radius: 6upx;
		display: block;
	}

	.cu-list.menu-avatar>.cu-item:after,
	.cu-list.menu>.cu-item:after {
		border-bottom: none;
	}

	.container {
		background-color: #f3f4f6;
		// padding: 10px;
		box-sizing: boder-box;
		height: 83vh;

		.todo_list {
			.todo_list_item {
				background-color: #fff;

				margin-bottom: 10px;
				//   border-radius: 5px;
				display: flex;
				// align-items: center;
				flex-direction: column;


				.todo_list_item_top {
					padding: 10px;

					display: flex;
					flex-direction: row;
					overflow: hidden;
					flex: 5;

					.todo_list_item_left {
						flex: 3;
						display: flex;
						flex-direction: column;
						border-bottom: 1px solid #f3f4f6;

						.todo_list_item_left_top {
							font-size: 16px;
							line-height: 18px;
							overflow: hidden;
							text-overflow: ellipsis;
							height: 20px;
							display: -webkit-box;
							-webkit-box-orient: vertical;
							-webkit-line-clamp: 1;
							word-break: break-all;
							color: #303133;
						}

						.todo_list_item_left_bottom {
							height: 48px;
							overflow: hidden;
							text-overflow: ellipsis;
							display: -webkit-box;
							-webkit-box-orient: vertical;
							-webkit-line-clamp: 3;
							word-break: break-all;
							line-height: 16px;
							font-size: 14px;
							color: #606266;
							margin-top: 5px;
						}
					}

					.todo_list_item_right {
						height: 74px;
						flex: 1;
						display: flex;
						flex-direction: column;

						.todo_list_item_right_top {
							flex: 1;
							display: flex;
							flex-direction: row;
						}

						.todo_list_item_right_bottom {
							flex: 1;
							display: flex;
							flex-direction: row;
						}
					}
				}

				.todo_list_item_bottom {
					flex: 2;
					display: flex;
					flex-direction: row;

					.todo_list_item_bottom_left {
						flex: 3;
					}

					.todo_list_item_bottom_right {
						flex: 1;
					}
				}
			}
		}
	}

	.grid_item {
		width: 100%;
		height: 100%;
		display: flex;
		align-content: center;
		justify-content: center;
		border-left: 1px solid #f4f4f5;
		border-bottom: 1px solid #f4f4f5;
		box-sizing: border-box;
	}

	.line {
		background: #ffffff;
		height: 2px;
		display: flex;
	}

	.line_item {
		background: #dbf1e1;
		margin-right: 1px;
		height: 2px;
		box-sizing: border-box;
	}

	.line_red {
		background: red;

	}

	.line_green {
		background: green;

	}

	.wei.cu-tag.badge {
		border-radius: 200rpx;
		position: absolute;
		top: -19rpx;
		right: -30rpx;
		font-size: 16rpx;
		padding: 0rpx 10rpx;
		height: 28rpx;
		color: #ffffff;
		z-index: 999;
	}
	.wei_card_item{
		border-radius: 10rpx;
		overflow: hidden;
	}
</style>
